﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using Infragistics.Win.UltraWinCalcManager;

namespace ATA.Winforms
{
    public partial class FormBaoCaoChietKhauThang : ATA.Winforms.frmChietkhau
    {
        private bool _calculateInstantPaymentDiscount = true;
        private bool _categoryReportOnly = false;
        ATA.Data.MisaDAL.DAL dal;


        public FormBaoCaoChietKhauThang()
        {
            InitializeComponent();
        }

        private void FormBaoCaoChietKhauThang_Load(object sender, EventArgs e)
        {
            dal = new ATA.Data.MisaDAL.DAL(ConfigurationManager.ConnectionStrings["misaConnectionString"].ConnectionString, ConfigurationManager.ConnectionStrings["netTiersConnectionString"].ConnectionString);

            txtMonthYear.Value = string.Format("{0}/{1}", DateTime.Now.Month, DateTime.Now.Year);

            BindDiscountList();
        }

        private void BindDiscountList()
        {
            try
            {
                ddlDiscount.DataSource = null;
                ddlDiscount.DataBind();

                var monthYear = txtMonthYear.Text.Split('/');
                int month = int.Parse(monthYear[0]);
                int year = int.Parse(monthYear[1]);

                var listDiscount = dal.GetListChietKhau(month, year);
                var result = new List<ATA.Data.MisaDAL.ChietKhau>();
                var discountIdList = new List<Guid>();

                //filter discount dau tien cua list discount bac thang
                foreach (var item in listDiscount)
                {
                    if (discountIdList.Exists(m => (m == item.Id)))
                        continue;

                    discountIdList.Add(item.Id);

                    result.Add(item);
                }

                ddlDiscount.DataSource = result;
                ddlDiscount.ValueMember = "ID";
                ddlDiscount.DisplayMember = "Name";
                ddlDiscount.DisplayLayout.Bands[0].Columns["ID"].Hidden = true;
                ddlDiscount.DisplayLayout.Bands[0].Columns["DiscountPercent"].Hidden = true;
                ddlDiscount.DisplayLayout.Bands[0].Columns["RequiredAmount"].Hidden = true;
                ddlDiscount.DisplayLayout.Bands[0].Columns["StartDate"].Hidden = true;
                ddlDiscount.DisplayLayout.Bands[0].Columns["EndDate"].Hidden = true;
                ddlDiscount.DisplayLayout.Bands[0].Columns["ToanTuSoSanh"].Hidden = true;
                ddlDiscount.DisplayLayout.Bands[0].Columns["ItemName"].Hidden = true;
                ddlDiscount.DisplayLayout.Bands[0].Columns["ItemType"].Hidden = true;
                ddlDiscount.DisplayLayout.Bands[0].Columns["Name"].Width = 250;

                ddlDiscount.DataBind();
                if (ddlDiscount.Rows.Count > 0)
                    ddlDiscount.SelectedRow = ddlDiscount.Rows.First();
            }
            catch
            {
            }
        }

        public override void btnGenData_Click(object sender, EventArgs e)
        {
            try
            {
                _calculateInstantPaymentDiscount = true;
                var monthYear = txtMonthYear.Text.Split('/');
                int month = int.Parse(monthYear[0]);
                int year = int.Parse(monthYear[1]);

                var bindList = new List<ATA.Data.MisaDAL.DoanhSoBanHang>();

                var discount = dal.GetListChietKhau(month, year).Where(m => m.Id == (Guid)ddlDiscount.Value && m.ItemType == ddlDiscount.SelectedRow.Cells["ItemType"].Text);

                if (discount.Count() == 0)
                    return;

                if (discount.Count() >= 1 && discount.First().ToanTuSoSanh == string.Empty)
                {
                    _calculateInstantPaymentDiscount = true;
                    _categoryReportOnly = false;

                    var resultlist = dal.GetDoanhSoTheoDonHang(month, year, (Guid)cboCustomers.Value);

                    foreach (var item in resultlist)
                    {
                        item.ChietKhauPhanTram = GetDiscountAmount(item, discount.ToList());

                        item.ChietKhauTienNhanh = GetInstantPaidDiscountPercent(item);

                        if (item.ChietKhauPhanTram != -1)
                            bindList.Add(item);
                    }
                }
                else if (discount.Count() > 1 && discount.First().ToanTuSoSanh != string.Empty)
                    //chiet khau bac thang
                {
                    _calculateInstantPaymentDiscount = false;
                    _categoryReportOnly = true;

                    var doanhsolist = dal.GetDoanhSoTheoDonHang(month, year, (Guid)cboCustomers.Value);

                    var resultlist = GetDoanhSoTheoThang(doanhsolist);


                    foreach (var item in resultlist)
                    {
                        item.ChietKhauPhanTram = GetDiscountPercent(item, discount);
                        if (item.ChietKhauPhanTram >= 0)
                            bindList.Add(item);
                    }
                }


                grdResults.DataSource = bindList;
                grdResults.DataBind();

                base.btnGenData_Click(sender, e);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private List<ATA.Data.MisaDAL.DoanhSoBanHang> GetDoanhSoTheoThang(List<ATA.Data.MisaDAL.DoanhSoBanHang> doanhsolist)
        {
            var resultlist = new List<ATA.Data.MisaDAL.DoanhSoBanHang>();
            foreach (var item in doanhsolist)
            {
                item.ChietKhauTienNhanh = GetInstantPaidDiscountPercent(item);
            }

            foreach (var customer in doanhsolist.Select(m => m.MaKH).Distinct())
            {
                foreach (var itemcategory in doanhsolist.Where(m => m.MaKH == customer).Select(m => m.PhanloaiHang).Distinct())
                {
                    resultlist.Add(GetDoanhSoTheoThang(doanhsolist, customer, itemcategory));
                }
            }
            return resultlist;
        }

        private ATA.Data.MisaDAL.DoanhSoBanHang GetDoanhSoTheoThang(List<ATA.Data.MisaDAL.DoanhSoBanHang> doanhsolist, string customer, string itemcategory)
        {
            var result = new ATA.Data.MisaDAL.DoanhSoBanHang();

            try
            {
                
                var temp = doanhsolist.Exists((m => m.MaKH == customer && m.PhanloaiHang == itemcategory)) ? doanhsolist.First(m => m.MaKH == customer && m.PhanloaiHang == itemcategory) : null;


                if (temp == null)
                    return null;

                result.TenHang = temp.PhanloaiHang;
                result.MaHang = temp.PhanloaiHang;
                result.PhanloaiHang = temp.PhanloaiHang;
                result.MaKH = temp.MaKH;
                result.TenKH = temp.TenKH;
                result.ChatLuong = temp.ChatLuong;
                result.LoaiSanPham = temp.LoaiSanPham;
                result.DoanhSo = doanhsolist.Where(m => m.MaKH == customer && m.PhanloaiHang == itemcategory).Sum(m => m.DoanhSo);

                result.TongChietKhauTienNhanh = doanhsolist.Where(m => m.MaKH == customer && m.PhanloaiHang == itemcategory).Sum(m => m.DoanhSo * m.ChietKhauTienNhanh / 100);
            }
            catch (Exception)
            {
                throw;
            }

            return result;
        }

        private decimal GetInstantPaidDiscountPercent(ATA.Data.MisaDAL.DoanhSoBanHang item)
        {
            decimal result = 0;

            if (item.TienThanhToan >= item.TienChuaThanhToan && (item.NgayThanhToan - item.NgayHoaDon) < new TimeSpan(24, 0, 0))
                result = 5;

            return result;
        }

        private decimal GetDiscountPercent(ATA.Data.MisaDAL.DoanhSoBanHang item, IEnumerable<ATA.Data.MisaDAL.ChietKhau> discountList)
        {
            discountList = discountList.OrderByDescending(m => m.RequiredAmount);
            decimal result = 0;
            foreach (var discount in discountList)
            {
                switch (discount.ToanTuSoSanh)
                {
                    case "<":
                        if (item.DoanhSo < discount.RequiredAmount)
                            result = discount.DiscountPercent;
                        break;
                    case "<=":
                        if (item.DoanhSo <= discount.RequiredAmount)
                            result = discount.DiscountPercent;

                        break;
                    case "=":
                        if (item.DoanhSo == discount.RequiredAmount)
                            result = discount.DiscountPercent;
                        break;
                    case ">=":
                        if (item.DoanhSo >= discount.RequiredAmount)
                            result = discount.DiscountPercent;
                        break;
                    case ">":
                        if (item.DoanhSo > discount.RequiredAmount)
                            result = discount.DiscountPercent;
                        break;
                    default:
                        break;
                }
            }

            if (!item.PhanloaiHang.Replace("FANIC", "JAJ").Contains(discountList.First().ItemType))
                return -1;

            return result;
        }

        private decimal GetDiscountAmount(ATA.Data.MisaDAL.DoanhSoBanHang item, List<ATA.Data.MisaDAL.ChietKhau> discounts)
        {
            bool amountOk = false;
            if (discounts.Count <= 0 
                || string.IsNullOrEmpty(item.PhanloaiHang)
                || string.IsNullOrEmpty(item.ChatLuong)
                || string.IsNullOrEmpty(item.LoaiSanPham)
                || !discounts.First().ItemType.Contains(item.PhanloaiHang.Replace("FANIC", "JAJ")))
                return -1;

            decimal quantity = item.SoLuong;

            var discount = from m in discounts
                                       where m.ItemType.Contains(item.PhanloaiHang.Replace("FANIC", "JAJ")) && !string.IsNullOrEmpty(item.PhanloaiHang)
                                            && m.ItemType.Contains(item.ChatLuong) && !string.IsNullOrEmpty(item.ChatLuong)
                                            && m.ItemType.Contains(item.LoaiSanPham) && !string.IsNullOrEmpty(item.LoaiSanPham)
                                       select m;

            if (discount.Count() == 0 || discount.Count() > 1)
                return 0;


            if (item.DonVi.Contains("L1L") || item.DonVi.Contains("L4L") || item.DonVi.Contains("L4.5L") || item.DonVi.Contains("L5L"))
            {
                //ruagiahaosac: 4 lon 4l = 1 thung 18l
                //ruagiahaosac: 4l 5l = 1 thung 18l
                //ruagiahaosac: 4 lon 4.5 lit = 1 thu`ng 18 lit
                //ruagiahaosac: va` 6 lon 1lit = 1 thu`ng 18lit
                switch (item.DonVi)
                {
                    case "L1L":
                        quantity = item.SoLuong / 6;
                        break;
                    case "L4L":
                        quantity = item.SoLuong / 4;
                        break;
                    case "L4.5L":
                        quantity = item.SoLuong / 4;
                        break;
                    case "L5L":
                        quantity = item.SoLuong / 4;
                        break;
                    case "T18L":
                        quantity = item.SoLuong;
                        break;
                }
            }

            if (quantity > discount.First().RequiredAmount)
                amountOk = true;

            if (amountOk)
                return discount.First().DiscountPercent;

            return 0;
        }

        private void grdResults_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            try
            {

                var calcManager = new UltraCalcManager(this.Container);
                var monthYear = txtMonthYear.Text.Split('/');
                int month = int.Parse(monthYear[0]);
                int year = int.Parse(monthYear[1]);

                e.Layout.Grid.CalcManager = calcManager;

                e.Layout.Bands[0].Columns["Discount"].Formula = "[DoanhSo]*[ChietKhauPhanTram]/100";
                e.Layout.Bands[0].Columns["TransFee"].Formula = "[DoanhSo]*" + ((int)txtTransFee.Value).ToString() + "/100";

                if (_calculateInstantPaymentDiscount)
                    e.Layout.Bands[0].Columns["ThuongChietKhauThanhToanTienNhanh"].Formula = "[DoanhSo]*[ChietKhauTienNhanh]/100";
                else e.Layout.Bands[0].Columns["ThuongChietKhauThanhToanTienNhanh"].Formula = "[TongChietKhauTienNhanh]";

                e.Layout.Bands[0].Columns["TongGiamTru"].Formula = "[Discount] + [TransFee] + [ThuongChietKhauThanhToanTienNhanh] + [HoTroVanChuyen] + [HoTroKhac]";


                grdResults.DisplayLayout.Bands[0].SortedColumns.Add("TenKH", true, true);

                if (!_categoryReportOnly)
                {
                    grdResults.DisplayLayout.Bands[0].SortedColumns.Add("ChatLuong", true, true);
                    grdResults.DisplayLayout.Bands[0].SortedColumns.Add("LoaiSanPham", true, true);
                }
                else
                {
                    grdResults.DisplayLayout.Bands[0].Columns["LoaiSanPham"].Hidden = true;
                    grdResults.DisplayLayout.Bands[0].Columns["PhanLoaiHang"].Hidden = true;
                    grdResults.DisplayLayout.Bands[0].Columns["ChatLuong"].Hidden = true;
                }

                e.Layout.Bands[0].Summaries.Clear();
                e.Layout.Bands[0].Summaries.Add(Infragistics.Win.UltraWinGrid.SummaryType.Sum, e.Layout.Bands[0].Columns["TongGiamTru"]);

                e.Layout.Bands[0].SummaryFooterCaption = "Tổng giảm trừ";
                e.Layout.Bands[0].Summaries[0].SummaryDisplayArea = Infragistics.Win.UltraWinGrid.SummaryDisplayAreas.InGroupByRows & Infragistics.Win.UltraWinGrid.SummaryDisplayAreas.Bottom & Infragistics.Win.UltraWinGrid.SummaryDisplayAreas.HideDataRowFooters;
            }
            catch
            {
            }
        }

        private void txtMonthYear_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                BindDiscountList();
            }
            catch
            {
            }
        }

        private void txtMonthYear_MaskValidationError(object sender, Infragistics.Win.UltraWinMaskedEdit.MaskValidationErrorEventArgs e)
        {

        }

    }
}
